/*
 * JavaScript file
 */

var output;

function init()
{
	//	Add your code stpes here
	output = document.getElementById('output');
	document.getElementById('friends_view').style.display = 'none';
}

var username = '';
var acceptFriends = 'uninitialized';

function updateFriendsRequestResponse()
{
	if (acceptFriends)
	{
		NfcServer.setResponse("FriendRQ", "ACC:" + username);
	}
	else
	{
		NfcServer.setResponse("FriendRQ", "DEC:" + username);
	}
}

function acceptFriendsChange()
{
	output.innerHTML = "acceptFriendsChange ";
	var newAcceptFriends = document.getElementById("acceptfriends").checked;
	if (newAcceptFriends != acceptFriends)
	{
		acceptFriends = newAcceptFriends;
		updateFriendsRequestResponse();
	}
}

function login()
{
	username = document.getElementById("username").value;
	if (username != "")
	{
		document.getElementById('login').style.display = 'none';
		var friends_view = document.getElementById('friends_view');
		friends_view.style.display = 'block';
		friends_view.innerHTML = "<p>Logged in as: " + username + ".</p>" + friends_view.innerHTML;
		NfcServer.sendMessage("FriendRQ", username);
		acceptFriendsChange()
		getP2PLog();
	}
}

function getP2PLog()
{
	NfcServer.transactionLog(
		function(text)
		{
		    // Parse JSON with a parser instead of eval call in real consumer applications
			var log = eval('(' + text + ')');
			var html = "";
			for (var i in log)
			{
				var message = log[i];
				if (message.messageId == "FriendRQ")
				{
					if (message.type == "responseReceived")
					{
						if (message.content.length >= 4 && message.content.substr(0,4) == "ACC:")
						{
							html += "<P>" + message.content.substring(4) + " accepted friends request.</p>";
						}
						if (message.content.length >= 4 && message.content.substr(0,4) == "DEC:")
						{
							html += "<P>" + message.content.substring(4) + " does not accept friends requests.</p>";
						}
					}
				}
			}
			output.innerHTML = html;
			setTimeout("getP2PLog()", 3000);
		},
		function (err)
		{
			output.innerHTML = "Error: "+ err.status + ". The APIBridge returned error: "+err.responseText+"<br/>";
		}
	);
}

